<?php
/**
 * 3-4岁专区认知内容示例编辑页面
 */
require_once '../../../admin/check_session.php';
require_once '../../../includes/config.php';
require_once '../includes/CognitiveManager34.php';
require_once '../../../includes/MediaManager.php';

// 创建认知管理器实例
$cognitiveManager = new CognitiveManager34();
$mediaManager = new MediaManager();

// 检查内容ID参数
if (!isset($_GET['content_id']) || !isset($_GET['module_id'])) {
    // 如果没有提供内容ID或模块ID，重定向到模块列表页面
    header("Location: cognitive_modules.php");
    exit;
}

$contentId = (int)$_GET['content_id'];
$moduleId = (int)$_GET['module_id'];

// 获取模块信息
$module = $cognitiveManager->getModuleById($moduleId);
if (!$module) {
    // 如果模块不存在或不属于3-4岁年龄段，重定向到模块列表页面
    header("Location: cognitive_modules.php?error=invalid_module");
    exit;
}

// 获取内容信息
$content = $cognitiveManager->moduleManager->getContentById($contentId);
if (!$content || $content['module_id'] != $moduleId) {
    // 如果内容不存在或不属于当前模块，重定向到内容列表页面
    header("Location: cognitive_contents.php?module_id={$moduleId}&error=invalid_content");
    exit;
}

// 初始化示例数据
$example = [
    'example_id' => 0,
    'content_id' => $contentId,
    'example_title' => '',
    'description' => '',
    'image_path' => '',
    'audio_id' => null,
    'example_order' => 0,
    'is_active' => 1
];

// 检查是否是编辑现有示例
$isEditing = false;
if (isset($_GET['id'])) {
    $exampleId = (int)$_GET['id'];
    $existingExample = $cognitiveManager->moduleManager->getExampleById($exampleId);
    
    if ($existingExample && $existingExample['content_id'] == $contentId) {
        $example = $existingExample;
        $isEditing = true;
    }
}

// 获取已上传的音频文件（如果有）
$exampleAudio = null;
if (!empty($example['audio_id'])) {
    $exampleAudio = $mediaManager->getMediaById($example['audio_id']);
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 收集表单数据
    $exampleData = [
        'content_id' => $contentId,
        'example_title' => $_POST['example_title'],
        'description' => $_POST['description'],
        'example_order' => (int)$_POST['example_order'],
        'is_active' => isset($_POST['is_active']) ? 1 : 0
    ];
    
    // 处理图片上传
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = "uploads/cognitive/examples/{$moduleId}/{$contentId}/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        $fileExtension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $newFileName = uniqid() . '.' . $fileExtension;
        $targetFile = $uploadDir . $newFileName;
        
        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
            $exampleData['image_path'] = $targetFile;
        } else {
            $errorMessage = "上传图片文件时出错";
        }
    } else if (!empty($example['image_path']) && !isset($_POST['remove_image'])) {
        $exampleData['image_path'] = $example['image_path'];
    } else if (isset($_POST['remove_image'])) {
        $exampleData['image_path'] = '';
    }
    
    // 处理音频上传
    if (isset($_FILES['audio']) && $_FILES['audio']['error'] === UPLOAD_ERR_OK) {
        $audioFile = $_FILES['audio'];
        $uploadResult = $mediaManager->uploadMedia($audioFile, 'audio', "cognitive/examples/{$moduleId}/{$contentId}");
        
        if ($uploadResult && isset($uploadResult['media_id'])) {
            $exampleData['audio_id'] = $uploadResult['media_id'];
        } else {
            $errorMessage = "上传音频文件时出错";
        }
    } else if (isset($_POST['remove_audio']) && $_POST['remove_audio'] == 1) {
        $exampleData['audio_id'] = null;
    } else if (!empty($example['audio_id'])) {
        $exampleData['audio_id'] = $example['audio_id'];
    }
    
    // 验证必填字段
    $errors = [];
    if (empty($exampleData['example_title'])) {
        $errors[] = "示例标题不能为空";
    }
    
    // 如果没有错误，保存数据
    if (empty($errors) && !isset($errorMessage)) {
        if ($isEditing) {
            // 更新现有示例
            $result = $cognitiveManager->moduleManager->updateExample($exampleId, $exampleData);
            
            if ($result) {
                $successMessage = "示例已成功更新";
                // 重新加载示例数据
                $example = $cognitiveManager->moduleManager->getExampleById($exampleId);
                if (!empty($example['audio_id'])) {
                    $exampleAudio = $mediaManager->getMediaById($example['audio_id']);
                } else {
                    $exampleAudio = null;
                }
            } else {
                $errorMessage = "更新示例时出错";
            }
        } else {
            // 添加新示例
            $newExampleId = $cognitiveManager->addExample($exampleData);
            
            if ($newExampleId) {
                // 重定向到示例列表页面
                header("Location: content_examples.php?content_id={$contentId}&module_id={$moduleId}&success=1");
                exit;
            } else {
                $errorMessage = "添加示例时出错";
            }
        }
    }
}

// 添加页面标题
$pageTitle = $isEditing ? "编辑 "{$example['example_title']}"" : "添加新示例";
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - KidsMind管理后台</title>
    <!-- 引入管理后台通用样式 -->
    <link rel="stylesheet" href="/admin/css/admin.css">
    <link rel="stylesheet" href="/admin/css/bootstrap.min.css">
    <link rel="stylesheet" href="/admin/css/fontawesome.min.css">
    <!-- 3-4岁专用样式 -->
    <style>
        .form-card {
            border-radius: 15px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            background-color: #fff;
            padding: 30px;
            margin-bottom: 30px;
        }
        .preview-card {
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
            background-color: <?php echo getColorCode($module['background_color']); ?>;
        }
        .preview-title {
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .preview-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 10px;
            margin-bottom: 15px;
            border: 2px solid #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .audio-preview {
            margin-top: 15px;
            padding: 10px;
            background-color: rgba(255,255,255,0.5);
            border-radius: 10px;
        }
        .audio-preview audio {
            width: 100%;
            border-radius: 8px;
        }
        .upload-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }
        .upload-wrapper input[type=file] {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }
        .breadcrumb-nav {
            margin-bottom: 20px;
        }
        .breadcrumb-item a {
            text-decoration: none;
            color: inherit;
        }
        .breadcrumb-item a:hover {
            color: #0d6efd;
        }
        .content-color {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
            vertical-align: middle;
            border: 1px solid #fff;
        }
        .placeholder-image {
            width: 100%;
            height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f8f9fa;
            border-radius: 10px;
            border: 2px dashed #dee2e6;
            color: #6c757d;
        }
        /* 马卡龙色系配色 */
        .bg-pastel-pink { background-color: #FFD6E0; }
        .bg-pastel-blue { background-color: #D6E5FF; }
        .bg-pastel-green { background-color: #D6FFE1; }
        .bg-pastel-yellow { background-color: #FFEFD6; }
        .bg-pastel-purple { background-color: #E9D6FF; }
    </style>
</head>
<body>
    <?php include '../../../admin/includes/header.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <?php include '../../../admin/includes/sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2"><?php echo $pageTitle; ?></h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <a href="content_examples.php?content_id=<?php echo $contentId; ?>&module_id=<?php echo $moduleId; ?>" class="btn btn-sm btn-outline-secondary">
                                <i class="fas fa-arrow-left"></i> 返回示例列表
                            </a>
                        </div>
                    </div>
                </div>
                
                <!-- 面包屑导航 -->
                <nav aria-label="breadcrumb" class="breadcrumb-nav">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item">
                            <a href="cognitive_modules.php">认知模块</a>
                        </li>
                        <li class="breadcrumb-item">
                            <a href="cognitive_contents.php?module_id=<?php echo $moduleId; ?>">
                                <?php echo htmlspecialchars($module['module_name']); ?>
                            </a>
                        </li>
                        <li class="breadcrumb-item">
                            <a href="content_examples.php?content_id=<?php echo $contentId; ?>&module_id=<?php echo $moduleId; ?>">
                                <?php echo htmlspecialchars($content['content_title']); ?> 的示例
                            </a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">
                            <?php echo $isEditing ? "编辑示例" : "添加示例"; ?>
                        </li>
                    </ol>
                </nav>
                
                <?php if (isset($successMessage)): ?>
                <div class="alert alert-success" role="alert">
                    <?php echo $successMessage; ?>
                </div>
                <?php endif; ?>
                
                <?php if (isset($errorMessage)): ?>
                <div class="alert alert-danger" role="alert">
                    <?php echo $errorMessage; ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger" role="alert">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo $error; ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-card">
                            <form method="post" action="" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label for="example_title" class="form-label">示例标题 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <?php if (!empty($content['color_code'])): ?>
                                        <span class="input-group-text">
                                            <span class="content-color" style="background-color: <?php echo $content['color_code']; ?>"></span>
                                        </span>
                                        <?php endif; ?>
                                        <input type="text" class="form-control" id="example_title" name="example_title" 
                                               value="<?php echo htmlspecialchars($example['example_title']); ?>" required>
                                    </div>
                                    <div class="form-text">例如："红苹果"、"蓝色的天空"等</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="description" class="form-label">示例描述</label>
                                    <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($example['description']); ?></textarea>
                                    <div class="form-text">简洁描述该示例，适合3-4岁儿童理解</div>
                                </div>
                                
                                <div class="mb-4">
                                    <label class="form-label">示例图片</label>
                                    <?php if (!empty($example['image_path'])): ?>
                                    <div class="mb-3">
                                        <img src="/<?php echo $example['image_path']; ?>" class="img-fluid rounded" style="max-height: 200px;">
                                        <div class="form-check mt-2">
                                            <input class="form-check-input" type="checkbox" id="remove_image" name="remove_image" value="1">
                                            <label class="form-check-label" for="remove_image">移除图片</label>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    <div class="upload-wrapper">
                                        <button class="btn btn-outline-primary" type="button"><?php echo !empty($example['image_path']) ? '替换图片' : '上传图片'; ?></button>
                                        <input type="file" name="image" accept="image/*">
                                    </div>
                                    <div class="form-text">上传展示该示例的图片，建议尺寸大小为600x400像素</div>
                                </div>
                                
                                <div class="mb-4">
                                    <label class="form-label">示例音频</label>
                                    <?php if ($exampleAudio): ?>
                                    <div class="mb-2">
                                        <div class="d-flex align-items-center">
                                            <audio controls src="<?php echo $exampleAudio['file_path']; ?>"></audio>
                                            <div class="form-check ms-3">
                                                <input class="form-check-input" type="checkbox" id="remove_audio" name="remove_audio" value="1">
                                                <label class="form-check-label" for="remove_audio">移除音频</label>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    <div class="upload-wrapper">
                                        <button class="btn btn-outline-primary" type="button"><?php echo $exampleAudio ? '替换音频' : '上传音频'; ?></button>
                                        <input type="file" name="audio" accept="audio/*">
                                    </div>
                                    <div class="form-text">上传朗读示例标题的音频，帮助孩子理解示例</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="example_order" class="form-label">显示顺序</label>
                                    <input type="number" class="form-control" id="example_order" name="example_order" 
                                           value="<?php echo (int)$example['example_order']; ?>" min="0">
                                    <div class="form-text">数字越小，显示越靠前</div>
                                </div>
                                
                                <div class="mb-4 form-check">
                                    <input type="checkbox" class="form-check-input" id="is_active" name="is_active" 
                                           <?php echo $example['is_active'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_active">激活示例</label>
                                </div>
                                
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <a href="content_examples.php?content_id=<?php echo $contentId; ?>&module_id=<?php echo $moduleId; ?>" class="btn btn-outline-secondary me-md-2">取消</a>
                                    <button type="submit" class="btn btn-primary">保存示例</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="sticky-top" style="top: 80px;">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0">示例预览</h5>
                                </div>
                                <div class="card-body">
                                    <div class="preview-card">
                                        <div class="preview-title">
                                            <span id="preview-title"><?php echo htmlspecialchars($example['example_title'] ?: '示例标题'); ?></span>
                                        </div>
                                        
                                        <?php if (!empty($example['image_path'])): ?>
                                        <img src="/<?php echo $example['image_path']; ?>" id="preview-image" class="preview-image">
                                        <?php else: ?>
                                        <div id="preview-image-placeholder" class="placeholder-image">
                                            <span><i class="fas fa-image me-2"></i> 无图片</span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <p id="preview-description" class="text-muted">
                                            <?php echo nl2br(htmlspecialchars($example['description'] ?: '示例描述将显示在这里...')); ?>
                                        </p>
                                        
                                        <?php if ($exampleAudio): ?>
                                        <div class="audio-preview">
                                            <small class="d-block mb-1 text-muted">示例音频:</small>
                                            <audio controls src="<?php echo $exampleAudio['file_path']; ?>"></audio>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">提示</h5>
                                </div>
                                <div class="card-body">
                                    <ul class="mb-0">
                                        <li>示例标题应简洁明了，直观表达示例内容</li>
                                        <li>选择符合主题的清晰图片，帮助孩子视觉识别</li>
                                        <li>添加音频可以帮助孩子学习正确的发音</li>
                                        <li>描述应简单易懂，适合3-4岁儿童理解</li>
                                        <li>良好的示例应该直观关联到所属的认知内容</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="/admin/js/bootstrap.bundle.min.js"></script>
    <script src="/admin/js/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            // 文件上传按钮显示所选文件名
            $('input[type="file"]').change(function(e) {
                if (e.target.files.length > 0) {
                    var fileName = e.target.files[0].name;
                    $(this).prev('button').text('已选择: ' + fileName);
                    
                    // 图片预览
                    if (e.target.name === 'image' && e.target.files[0]) {
                        var reader = new FileReader();
                        reader.onload = function(e) {
                            if ($('#preview-image').length) {
                                $('#preview-image').attr('src', e.target.result);
                            } else {
                                $('#preview-image-placeholder').html('<img src="' + e.target.result + '" id="preview-image" class="preview-image">');
                            }
                        }
                        reader.readAsDataURL(e.target.files[0]);
                    }
                }
            });
            
            // 移除图片复选框处理
            $('#remove_image').change(function() {
                if ($(this).is(':checked')) {
                    $('input[name="image"]').prop('disabled', true);
                    $('.upload-wrapper:first button').addClass('disabled');
                    $('#preview-image').hide();
                    $('#preview-image-placeholder').show();
                } else {
                    $('input[name="image"]').prop('disabled', false);
                    $('.upload-wrapper:first button').removeClass('disabled');
                    $('#preview-image').show();
                    $('#preview-image-placeholder').hide();
                }
            });
            
            // 移除音频复选框处理
            $('#remove_audio').change(function() {
                if ($(this).is(':checked')) {
                    $('input[name="audio"]').prop('disabled', true);
                    $('.upload-wrapper:eq(1) button').addClass('disabled');
                } else {
                    $('input[name="audio"]').prop('disabled', false);
                    $('.upload-wrapper:eq(1) button').removeClass('disabled');
                }
            });
            
            // 实时预览功能
            $('#example_title').on('input', function() {
                $('#preview-title').text($(this).val() || '示例标题');
            });
            
            $('#description').on('input', function() {
                $('#preview-description').html(($(this).val() || '示例描述将显示在这里...').replace(/\n/g, '<br>'));
            });
        });
    </script>
</body>
</html>

<?php
/**
 * 根据颜色名称获取颜色代码
 */
function getColorCode($colorName) {
    $colorMap = [
        'pink' => '#FFD6E0',
        'blue' => '#D6E5FF',
        'green' => '#D6FFE1',
        'yellow' => '#FFEFD6',
        'purple' => '#E9D6FF'
    ];
    
    return isset($colorMap[$colorName]) ? $colorMap[$colorName] : '#FFD6E0';
} 